<?php

namespace Biz\service\SuperSubsidy;

use Doraemon\service\DingTalkAlert;
use Doraemon\tools\Log;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Youzan;
use Biz\model\SuperSubsidy\YouZanBrandGoodsModel;

class YouZanGoodsInfo implements ConstInterface
{
    private $data = [];
    private $hasSku = false;//是否多规格
    private $kArr = [];//sku k（规格xiang） 数组对象
    private $vArr = [];//sku v（规格值） 数组对象
    private $skuSpecs = [];//sku 规格项-规格值 数组对象
    private $skus = [];//sku 详情信息（规格值组合的sku） 数组对象

    private $spuCode = '';//商品库商品的商品编码 BM开头
    private $spuInfo = [];//商品库商品信息

    private $itemId = '';//有赞商城item_id 商品id
    private $itemInfo = [];//有赞商城item 商品信息

    public function __construct($data, $spuCode = null)
    {
        $this->data = $data;
        $this->spuCode = $spuCode;
        if ($this->data['sku_info']) {
            $this->hasSku = true;
            $this->formatSkusParam($this->data['sku_info']['sku_specs'], $this->data['sku_info']['skus']);
        }
    }

    public function create($accountId)
    {
        $res = $this->createSpu($accountId);
        if (!$res) {
            Log::error('创建商品失败');
            throw new \Exception('创建商品失败');
        }
        return $res;
    }

    public function release()
    {
        $res = $this->releaseSpu();
        if (!$res) {
            Log::error('发布商品失败');
            throw new \Exception('发布商品失败');
        }
        return $res;
    }

    private function createSpu($accountId)
    {
        $createSpuParams = $this->getCreateSpuParams();
        //创建商品库
        $res = Youzan::spuCreate($createSpuParams);
        if ($res['code'] == 1 && $res['data']) {
            $this->spuCode = $res['data'];
        } else {
            Log::error('创建商品库失败#有赞API创建商品库失败');
            throw new \Exception('创建商品失败');
        }
        $this->getSpuInfo();
        if (!$this->spuInfo) {
            Log::error('查询商品库商品信息失败');
            throw new \Exception('创建商品失败，未查询到商品库信息');
        }
        //保存数据
        $addData = [
            'brand_user_id' => $accountId,
            'spu_code' => $this->spuCode,
            'spu_no' => $this->spuInfo['spu_no'],
            'name' => $createSpuParams['name'],
            'photo_url' => $createSpuParams['photo_url'],
            'category_id' => $createSpuParams['category_id'],
            'white_img' => $this->data['white_img'],
            'video_info' => $this->data['video_info'],
            'sell_point' => $this->data['sell_point'],
            'goods_service' => $this->data['goods_service'],
            'content' => $this->data['content'],
            'no_sku_info' => json_encode($this->data['no_sku_info']),
            'sku_info' => json_encode($this->data['sku_info']),
            'status' => YouZanBrandGoodsModel::STATUS_WAIT_RELEASE
        ];
        $res = YouZanBrandGoodsModel::insertData($addData);
        if (!$res) {
            Log::error('创建商品失败#数据库写入失败');
        }
        return $res;
    }

    private function releaseSpu()
    {
        $releaseSpuParams = $this->getReleaseParams();
        //发布网店商品
        $res = Youzan::spuRelease($releaseSpuParams);
        if ($res['code'] == 1 && $res['data']) {
            $itemId = $res['data']['item_id'];
            $updateData = [
                'item_id' => $itemId,
                'status' => YouZanBrandGoodsModel::STATUS_RELEASE,
            ];
            //保存数据
            $res = YouZanBrandGoodsModel::update($updateData, ['spu_code' => $this->spuCode]);
            if ($res) {
                return $itemId;
            } else {
                Log::error('发布网店商品失败#数据库更新数据失败');
                throw new \Exception('发布网店商品失败');
            }
        } else {
            Log::error('发布网店商品失败#有赞API发布网店商品失败');
            throw  new \Exception('发布网店商品失败');
        }
    }

    private function getCreateSpuParams()
    {
        $createSpuParams = [
            'name' => $this->data['name'],
            'unit' => '件',
            'category_id' => (int)$this->data['category_id'],
            'retail_price' => '99999',
            'photo_url' => $this->data['photo_url'],
        ];
        if ($this->hasSku) {
            $createSpuParams_spec_define_tuple = [];
            $createSpuParams_skus = [];
            foreach ($this->skuSpecs as $kId => $spec) {
                $tupleInfo = [
                    'key' => [
                        'k' => $spec['k'],
                        'kId' => $spec['kId'],
                    ],
                    'values' => []
                ];
                foreach ($spec['values'] as $vId => $value) {
                    $tupleInfo['values'][] = [
                        'v' => $value['v'],
                        'vId' => $value['vId']
                    ];
                }
                $createSpuParams_spec_define_tuple[] = $tupleInfo;
            }
            $createSpuParams['spec_define_tuple'] = json_encode($createSpuParams_spec_define_tuple);
            foreach ($this->skus as $spec_vid => $row) {
                $skusItem = [
                    'specs' => [],
                    'item_weight' => (int)($row['weight'] * 1000),
                    'standard_price' => (string)$row['market_price'],
                    'retail_price' => "99999"
                ];
                foreach ($row['specs'] as $spec) {
                    $skusItem['specs'][] = [
                        'name' => $spec['k'],
                        'value' => $spec['v']
                    ];
                }
                $createSpuParams_skus[] = $skusItem;
            }
            $createSpuParams['skus'] = $createSpuParams_skus;
        } else {
            $createSpuParams['standard_price'] = $this->data['market_price'];
        }
        return $createSpuParams;
    }

    private function getReleaseParams()
    {
        if (!$this->spuCode) {
            Log::error('不存在商品编码#spu_code:' . $this->spuCode);
            throw new \Exception('不存在商品编码');
        }
        $this->getSpuInfo();
        if (!$this->spuInfo) {
            Log::error('查询商品库商品信息失败');
            throw new \Exception('发布商品失败，未查询到商品库信息');
        }

        $content = json_decode($this->data['content'], true);
        $contentStr = '';
        foreach ($content as $row) {
            $contentStr .= '<p><img src="' . $row . '"/></p>';
        }

        //发布网店商品参数
        $releaseSpuParams = [
            'picture' => $this->data['photo_url'],
            'spu_code' => $this->spuCode,
            'components_extra_id' => 117922704,//商品页模版Id
            'sold_time' => 0,
            'title' => $this->data['name'],
            'is_virtual' => 0,
            'is_display' => 0,
            'pre_sale' => false,
            'tag_ids' => [],
            'price' => "99999",
            'purchase_right' => false,
            'hide_stock' => 1,
            'content' => $contentStr,
            'sell_point' => $this->data['sell_point']
        ];
        if ($this->hasSku) {
            $releaseSpu_sku_image = [];//发布商品sku图片
            foreach ($this->skuSpecs as $kId => $spec) {
                if ($spec['index'] == 0) {
                    $releaseSpu_sku_image = [
                        'dict_id' => $kId,
                        'dict_value' => $spec['k'],
                        'is_show' => true,
                        'img_urls' => [],
                    ];
                }
                foreach ($spec['values'] as $vId => $value) {
                    if ($spec['index'] == 0 && $value['url']) {
                        $releaseSpu_sku_image['img_urls'][] = [
                            'id' => $vId,
                            'img_url' => $value['url'],
                        ];
                    }
                }
            }
            $releaseSpu_sku_image = $releaseSpu_sku_image['img_urls'] ? $releaseSpu_sku_image : [];
            if ($releaseSpu_sku_image) {
                $releaseSpuParams['sku_image'] = $releaseSpu_sku_image;
            }
            $releaseSpuParams['stocks'] = [];
            $releaseSpuParams['item_sku_meas_props'] = [];
            $releaseSpuParams['origin'] = 0;
            $priceArr = [];
            foreach ($this->spuInfo['skus'] as $row) {
                $specVArr = explode(',', $row['specifications']);
                $vIds = [];
                foreach ($specVArr as $v) {
                    if (!isset($this->vArr[$v]) || !$this->vArr[$v]) {
                        Log::error('商品规格信息错误');
                        throw new \Exception('发布商品规格信息失败');
                    }
                    $vId = $this->vArr[$v]['vId'];
                    $k = $this->vArr[$v]['k'];
                    $kId = $this->vArr[$v]['kId'];
                    $vIds[] = $vId;
                }
                $specVid = implode('-', $vIds);
                if (isset($this->skus[$specVid]) && $this->skus[$specVid]) {
                    $stockItem = [
                        'skus' => $this->skus[$specVid]['specs'],
                        'related_spu_code' => $this->spuCode,
                        'price' => '99999',
                        'sell_stock_count' => (string)$this->skus[$specVid]['stock'],
                        'related_sku_code' => $row['sku_code']
                    ];
                    $weightItem = [
                        'sku_code' => $row['sku_code'],
                        'weight' => intval($this->skus[$specVid]['weight'] * 1000),
                    ];
                    for ($i = 0; $i < count($vIds); $i++) {
                        $s = 's' . ($i + 1);
                        $weightItem[$s] = $vIds[$i];
                    }
                    $releaseSpuParams['stocks'][] = $stockItem;
                    $releaseSpuParams['item_sku_meas_props'][] = $weightItem;

                    $priceArr[] = $this->skus[$specVid]['market_price'];
                } else {
                    Log::error('商品规格信息错误');
                    throw new \Exception('发布商品规格信息失败');
                }
                $releaseSpuParams['origin'] = $priceArr ? max($priceArr) : 0;
                $releaseSpuParams['origin'] = (string)$releaseSpuParams['origin'];
            }
        } else {
            //多规格，只需要传规格里的weight 和 stock。单规格，需要传 total_stock，item_weight
            $releaseSpuParams['item_weight'] = intval($this->data['no_sku_info']['item_weight'] * 1000);
            $releaseSpuParams['total_stock'] = (string)$this->data['no_sku_info']['total_stock'];
            $releaseSpuParams['origin'] = (string)$this->data['no_sku_info']['market_price'];
        }
        return $releaseSpuParams;
    }

    private function formatSkusParam(string $skuSpecsStr, string $skusStr)
    {
        $skuSpecsData = json_decode($skuSpecsStr, true);//规格项
        $skusData = json_decode($skusStr, true);//规格详情
        $kArr = [];
        $vArr = [];
        $skuSpecs = [];
        $skus = [];
        $kValuesCountArr = [];
        foreach ($skuSpecsData as $i => $row) {
            $kId = $i + 1;
            $skuSpecs[$kId] = [
                'kId' => $kId,
                'k' => $row['key']['k'],
                'index' => $i,
                'values' => []
            ];
            $kArr[$row['key']['k']] = ['k' => $row['key']['k'], 'kId' => $kId];
            foreach ($row['values'] as $j => $value) {
                $vId = intval($kId . ($j + 1));
                $tempArr = [
                    'vId' => $vId,
                    'v' => $value['v'],
                ];
                if (isset($value['url']) && $i == 0) {
                    $tempArr['url'] = $value['url'];
                }
                $skuSpecs[$kId]['values'][$vId] = $tempArr;
                $vArr[$value['v']] = ['v' => $value['v'], 'vId' => $vId, 'k' => $row['key']['k'], 'kId' => $kId];
            }
            $kValuesCountArr[$kId] = count($row['values']);
        }
        foreach ($skusData as $row) {
            $specKArr = [];
            $specKIdArr = [];
            $specVArr = [];
            $specVIdArr = [];
            foreach ($row['specs'] as $i => $spec) {
                if (!isset($kArr[$spec['name']]['kId']) || !$kArr[$spec['name']]['kId']) {
                    Log::error('规格项信息错误');
                    throw new \Exception('规格项信息错误');
                }
                $kId = $kArr[$spec['name']]['kId'];
                $specKArr[] = $spec['name'];
                $specKIdArr[] = $kId;

                if (!isset($vArr[$spec['value']]['vId']) || !$vArr[$spec['value']]['vId']) {
                    Log::error('规格项的值信息错误');
                    throw new \Exception('规格项值信息错误');
                }
                $vId = $vArr[$spec['value']]['vId'];
                $specVArr[] = $spec['value'];
                $specVIdArr[] = $vId;
                $row['specs'][$i] = [
                    'k' => $spec['name'],
                    'kid' => $kId,
                    'v' => $spec['value'],
                    'vid' => $vId
                ];
                $row['s' . ($i + 1)] = $vId;
            }
            $sku = $row;
            $sku['spec_kid'] = implode('-', $specKIdArr);
            $sku['spec_k'] = implode(',', $specKArr);
            $sku['spec_vid'] = implode('-', $specVIdArr);
            $sku['spec_v'] = implode(',', $specVArr);
            $skus[$sku['spec_vid']] = $sku;
        }
        $vCombineCount = array_product($kValuesCountArr);
        if (count($skus) != $vCombineCount) {
            Log::error('规格项和规格信息数量不一致');
            throw new \Exception('规格项和规格信息数量不一致');
        }
        $this->kArr = $kArr;
        $this->vArr = $vArr;
        $this->skuSpecs = $skuSpecs;
        $this->skus = $skus;
    }

    private function getSpuInfo()
    {
        if (!$this->spuInfo) {
            $this->spuInfo = Youzan::spuGet($this->spuCode);
        }
    }

    private function getItemInfo()
    {
        if (!$this->itemInfo) {
            $this->itemInfo = $this->itemId ? Youzan::getItem($this->itemId) : [];
        }
    }

    /**
     * 获取已发布商品对应的item信息
     * @param $itemId
     * @return array
     * @throws \Exception
     */
    public function getGoodsItemInfo($itemId)
    {
        $this->itemId = $itemId;
        $this->getItemInfo();
        $result = [];
        if ($this->hasSku) {
            foreach ($this->itemInfo['skus'] as $row) {
                $specArr = json_decode($row['properties_name_json'], true);
                $sku_id = $row['sku_id'];
                $vIds = [];
                $specificationsArr = [];
                foreach ($specArr as $spec) {
                    $v = $spec['v'];
                    if (!isset($this->vArr[$v]) || !$this->vArr[$v]) {
                        Log::error('获取对应商品规格信息错误');
                        throw new \Exception('获取对应商品规格信息错误');
                    }
                    $vId = $this->vArr[$v]['vId'];
                    $k = $this->vArr[$v]['k'];
                    $kId = $this->vArr[$v]['kId'];
                    $vIds[] = $vId;
                    $specificationsArr[] = $v;
                }
                $specVid = implode('-', $vIds);
                if (isset($this->skus[$specVid]) && $this->skus[$specVid]) {
                    $item = [
                        'spu_code' => $this->data['spu_code'],
                        'spu_no' => $this->data['spu_no'],
                        'item_id' => $itemId,
                        'title' => $this->data['name'],
                        'sku_id' => $sku_id,
                        'specifications' => implode(',', $specificationsArr),
                        'supply_price' => $this->skus[$specVid]['supply_price'],
                        'market_price' => $this->skus[$specVid]['market_price'],
                        'min_price' => $this->skus[$specVid]['min_price'],
                    ];
                    $result[] = $item;
                } else {
                    Log::error('获取商品规格信息错误');
                    throw new \Exception('获取商品规格信息错误');
                }
            }
        } else {
            $item = [
                'spu_code' => $this->data['spu_code'],
                'spu_no' => $this->data['spu_no'],
                'item_id' => $itemId,
                'title' => $this->data['name'],
                'supply_price' => $this->data['no_sku_info']['supply_price'] ?? '',
                'market_price' => $this->data['no_sku_info']['market_price'] ?? '',
                'min_price' => $this->data['no_sku_info']['min_price'] ?? '',
            ];
            $result[] = $item;
        }
        return $result;
    }

    private function getAttrExample()
    {
        $attrGroup = [
            ['白色', '红色', '黑色'],
            ['透气', '防滑'],
            ['38码', '39码'],
            ['男款', '女款']
        ];
        $count = count($attrGroup);
        $result = [];
        for ($i = 0; $i < $count - 1; $i++) {
            if ($i == 0) {
                $result = $attrGroup[0];
            }
            $temp = [];
            foreach ($result as $res) {
                $resArr = is_array($res) ? $res : [$res];
                foreach ($attrGroup[$i + 1] as $sec) {
                    $temp[] = array_merge($resArr, [$sec]);
                }
            }
            $result = $temp;
        }
        var_dump($result);
        return $result;
    }

    /**
     * 创建商品库 示例（仅供参考）
     * @return void
     */
    private function createSpuExample()
    {
        $params = [
            'name' => '测试创建商品22',
            'unit' => '件',
            'category_id' => 3033698,
            'retail_price' => "99999",
            'photo_url' => json_encode([
                [
                    "url" => "https://img01.yzcdn.cn/upload_files/2023/02/03/Fsz5wjq904MmuSnQ8L4KKMASO9Dn.png",
                    "height" => "500",
                    "id" => 5964745559,
                    "width" => "500"
                ]]),
            'skus' => [
                [
                    'specs' => [
                        [
                            'name' => '颜色',
                            'value' => '红色'
                        ],
                        [
                            'name' => '尺码',
                            'value' => '100*100'
                        ],
                    ],
                    'item_weight' => 500,
                    'standard_price' => "39",
                    'retail_price' => "49"
                ],
                [
                    'specs' => [
                        [
                            'name' => '颜色',
                            'value' => '绿色'
                        ],
                        [
                            'name' => '尺码',
                            'value' => '100*100'
                        ],
                    ],
                    'item_weight' => 500,
                    'standard_price' => "39",
                    'retail_price' => "49"
                ],
                [
                    'specs' => [
                        [
                            'name' => '颜色',
                            'value' => '红色'
                        ],
                        [
                            'name' => '尺码',
                            'value' => '120*120'
                        ],
                    ],
                    'item_weight' => 600,
                    'standard_price' => "45",
                    'retail_price' => "55"
                ],
                [
                    'specs' => [
                        [
                            'name' => '颜色',
                            'value' => '绿色'
                        ],
                        [
                            'name' => '尺码',
                            'value' => '120*120'
                        ],
                    ],
                    'item_weight' => 600,
                    'standard_price' => "45",
                    'retail_price' => "55"
                ]
            ],
            'spec_define_tuple' => json_encode([
                [
                    'key' => [
                        'k' => "颜色",
                        'kId' => 1
                    ],
                    'values' => [
                        [
                            'v' => '红色',
                            'vId' => 11
                        ],
                        [
                            'v' => '绿色',
                            'vId' => 12
                        ]
                    ]
                ],
                [
                    'key' => [
                        'k' => "尺码",
                        'kId' => 2
                    ],
                    'values' => [
                        [
                            'v' => '100*100',
                            'vId' => 21
                        ],
                        [
                            'v' => '120*120',
                            'vId' => 22
                        ]
                    ]
                ]
            ])
        ];
        $res = Youzan::spuCreate($params);
        var_dump($res);
    }

    /**
     * 发布网店商品  示例（仅供参考）
     * @return void
     */
    private function releaseSpuExample()
    {
        $params = [
            'picture' => json_encode([
                [
                    "url" => "https://img01.yzcdn.cn/upload_files/2023/02/03/Fsz5wjq904MmuSnQ8L4KKMASO9Dn.png",
                    "height" => "500",
                    "id" => 5964745559,
                    "width" => "500"
                ]]),
            'spu_code' => 'BM234743328577',
            'components_extra_id' => 117922704,//商品页模版Id
            'sold_time' => 0,
            'title' => '测试创建商品22-发布有规格商品222',
            'is_virtual' => 0,
            'is_display' => 0,
            'pre_sale' => false,
            'tag_ids' => [],
            'price' => "99999",
            'purchase_right' => false,
            'hide_stock' => 1,
            //'item_weight' => 500,
            'sku_image' => [
                'img_urls' => [
                    [
                        'id' => 11,
                        'img_url' => 'https://img01.yzcdn.cn/upload_files/2023/01/18/FnyM_OgWxVFUPRiwylIUi7_09zJX.png!small.webp',
                    ],
                    [
                        'id' => 12,
                        'img_url' => 'https://img01.yzcdn.cn/upload_files/2023/01/18/FmRKL7LPBFO67wt0pu_PCG6PijrQ.png',
                    ],
                ],
                'dict_id' => 1,
                'dict_value' => '颜色',
                'is_show' => true
            ],
            'stocks' => [
                [
                    'skus' => [
                        [
                            'k' => '颜色',
                            'kid' => 1,
                            'v' => '红色',
                            'vid' => 11,
                        ],
                        [
                            'k' => '尺码',
                            'kid' => 2,
                            'v' => '100*100',
                            'vid' => 21,
                        ]
                    ],
                    'related_spu_code' => 'BM234743328577',
                    'price' => '99999',
                    'sell_stock_count' => '10',
                    'related_sku_code' => 'BM234743328529198028904',
                ],
                [
                    'skus' => [
                        [
                            'k' => '颜色',
                            'kid' => 1,
                            'v' => '红色',
                            'vid' => 11,
                        ],
                        [
                            'k' => '尺码',
                            'kid' => 2,
                            'v' => '120*120',
                            'vid' => 22,
                        ]
                    ],
                    'related_spu_code' => 'BM234743328577',
                    'price' => '99999',
                    'sell_stock_count' => '10',
                    'related_sku_code' => 'BM234743328538198028906',
                ],
                [
                    'skus' => [
                        [
                            'k' => '颜色',
                            'kid' => 1,
                            'v' => '绿色',
                            'vid' => 12,
                        ],
                        [
                            'k' => '尺码',
                            'kid' => 2,
                            'v' => '100*100',
                            'vid' => 21,
                        ]
                    ],
                    'related_spu_code' => 'BM234743328577',
                    'price' => '99999',
                    'sell_stock_count' => '10',
                    'related_sku_code' => 'BM234743328572198028905',
                ],
                [
                    'skus' => [
                        [
                            'k' => '颜色',
                            'kid' => 1,
                            'v' => '绿色',
                            'vid' => 12,
                        ],
                        [
                            'k' => '尺码',
                            'kid' => 2,
                            'v' => '120*120',
                            'vid' => 22,
                        ]
                    ],
                    'related_spu_code' => 'BM234743328577',
                    'price' => '99999',
                    'sell_stock_count' => '10',
                    'related_sku_code' => 'BM234743328587198028907',
                ],
            ],
            'item_sku_meas_props' => [
                [
                    'sku_code' => 'BM234743328529198028904',
                    's1' => 11,
                    's2' => 21,
                    'weight' => 500,
                ],
                [
                    'sku_code' => 'BM234743328538198028906',
                    's1' => 11,
                    's2' => 22,
                    'weight' => 1000,
                ],
                [
                    'sku_code' => 'BM234743328572198028905',
                    's1' => 12,
                    's2' => 21,
                    'weight' => 1500,
                ],
                [
                    'sku_code' => 'BM234743328587198028907',
                    's1' => 12,
                    's2' => 22,
                    'weight' => 1500,
                ]
            ],
            'origin' => '399',
            'content' => '<p><img src="https://img01.yzcdn.cn/upload_files/2023/02/03/Fsz5wjq904MmuSnQ8L4KKMASO9Dn.png"/></p><p><img src="https://img01.yzcdn.cn/upload_files/2022/12/05/Fvrfo15WZuA85HPT8ESULW-N9IsJ.jpg"/></p><p><img src="https://img.alicdn.com/imgextra/i2/883075047/O1CN010fZfgH1n9ZWmqkcHP_!!883075047.jpg"/></p>',
            'sell_point' => '好用，好用',//商品卖点
            //'total_stock' => "50",
        ];
        //多规格，只需要传规格里的weight 和 stock。单规格，需要传 total_stock，item_weight
        $res = Youzan::spuRelease($params);
        var_dump($res);
        if ($res['code'] == 1 && $res['data']) {
            $spuCode = $res['data'];
        }
    }
}
